package com.may.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.may.entity.User;
import com.may.service.UserService;
import com.may.jwt.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author May
 * @date 2020/11/10 11:49
 */
@Slf4j
@RestController
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", user.getName()).eq("password", user.getPassword());
        User userDb = userService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(userDb)) {
            Map<String, String> payload = new HashMap<>();
            payload.put("id", userDb.getId().toString());
            payload.put("name", userDb.getName());
            // 生成token
            String accessToken = JWTUtil.getAccessToken(payload);
            String refreshToken = JWTUtil.getRefreshToken(payload);
            map.put("status", true);
            map.put("msg", "登陆成功");
            map.put("accessToken", accessToken);
            map.put("refreshToken", refreshToken);
        } else {
            map.put("status", false);
            map.put("msg", "登陆失败");
        }
        return map;
    }

    @PostMapping("/test")
    public Map<String, Object> test(@RequestHeader String token) {
        Map<String, Object> map = new HashMap<>();
        // 验证令牌
        DecodedJWT verify = JWTUtil.verify(token);
        System.out.println(verify.getClaim("id").asString());
        System.out.println(verify.getClaim("name").asString());
        map.put("status", true);
        map.put("msg", "请求成功");
        return map;
    }

    @GetMapping("/hello")
    public void hello() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 2);
        System.out.println(instance.getTime());
        System.out.println(LocalDateTime.now().plusMinutes(2));
    }
}
